<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label for="username">用户名：</label>
          <input
              v-model="form.username"
              type="text"
              id="username"
              class="form-input"
              placeholder="请输入用户名"
              required
          />
        </div>
        <div class="form-group">
          <label for="password">密码：</label>
          <input
              v-model="form.password"
              type="password"
              id="password"
              class="form-input"
              placeholder="请输入密码"
              required
          />
        </div>
        <button type="submit" class="login-button" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const router = useRouter()
const form = ref({
  username: '',
  password: ''
})
const loading = ref(false)

// 简单的token验证
function isValidToken(token) {
  if (!token || typeof token !== 'string') return false
  const parts = token.split('.')
  return parts.length === 3
}

const handleLogin = async () => {
  try {
    // 输入验证
    if (!form.value.username.trim() || !form.value.password.trim()) {
      throw new Error('请输入用户名和密码')
    }

    loading.value = true
    const response = await request.post('/api/auth/login', form.value)

    // Debug log: 查看后端返回的数据
    console.log('后端响应:', response)

    // 确保处理正确的数据结构
    const responseData = response.data // 这里你应该直接从 response.data 中获取数据

    if (responseData.code === 1) {
      // 检查 token 是否存在且有效
      if (responseData.data?.token && isValidToken(responseData.data.token)) {
        localStorage.setItem('token', responseData.data.token)

        // Debug log: 确认 token 是否保存成功
        console.log('Token 保存成功:', localStorage.getItem('token'))
        ElMessage.success('登录成功')

        const redirect = router.currentRoute.value.query.redirect || '/dashboard'

        // Debug log: 确认跳转路径
        console.log('跳转路径:', redirect)
        await router.push(redirect)
      } else {
        throw new Error('服务器返回了无效的token格式')
      }
    } else {
      throw new Error(responseData.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败')

    // 特殊处理Base64错误
    if (error.message.includes('base64')) {
      ElMessage.error('认证数据格式错误，请重试')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    form.value.username = rememberedUsername
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  padding: 40px 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: #555;
  font-weight: 500;
}

.form-input {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.login-button {
  padding: 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-button:hover:not(:disabled) {
  background-color: #66b1ff;
}

.login-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}
</style>
